package com.xd.common.filter;

import com.alibaba.fastjson.JSON;
import com.xd.common.exception.Result;
import com.xd.common.util.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author : k
 * @Date : 2022/3/24
 * @Desc : 认证的异常处理类
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {

        String errorMessage = (String) request.getAttribute("msg");
        Result result = null;
        if (errorMessage != null) {
            result = new Result(HttpStatus.UNAUTHORIZED.value(), errorMessage);
        } else {
            result = new Result(HttpStatus.UNAUTHORIZED.value(), "用户名认证失败请重新登录");
        }
        String json = JSON.toJSONString(result);
        //处理移除
        WebUtils.renderString(response, json);
    }
}
